import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;


public class ImageCode {
	public static byte[] getCodeByte(String url,HttpClient httpclient)
	  {
	   
	    HttpGet get = new HttpGet(url);
	    ByteArrayOutputStream baos = new ByteArrayOutputStream();
	    try {
	      HttpResponse response = httpclient.execute(get);
	      HttpEntity entity = response.getEntity();
//	      this.log.debug(response.getStatusLine());
	      if (entity != null) {
	        InputStream is = entity.getContent();
	        byte[] buf = new byte[1024];
	        int len = -1;
	        while ((len = is.read(buf)) > -1)
	          baos.write(buf, 0, len);
	      }
	    }
	    catch (Exception e) {
	     e.printStackTrace();
	    }
	   
	    return baos.toByteArray();
	  }

	public static  String getCode(String url,HttpClient  httpclient)
			    throws IOException
			  {
		
		Icon icon=new ImageIcon(getCodeByte(url,httpclient));
		String result=JOptionPane.showInputDialog(null,icon,"请输入验证码",JOptionPane.INFORMATION_MESSAGE); 
    
		  return result;
//		
//			    JFrame frame = new JFrame("验证码");
//			    JLabel label = new JLabel(new ImageIcon(getCodeByte(url,httpclient)), 0);
//
//			    frame.add(label);
//			    
//			    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
//			    frame.setSize(300, 200);
//			    frame.setLocationRelativeTo(null);
//			    frame.setVisible(true);
			
			  }
}
